package com.sdruixinggroup.mondayb2b.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.Classify;
import com.sdruixinggroup.mondayb2b.models.OpenAreas;
import com.sdruixinggroup.mondayb2b.ui.Activities.CityListActivity;
import com.sdruixinggroup.mondayb2b.ui.Activities.OpenAreaActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.sdruixinggroup.mondayb2b.widget.ClassifyTabView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.AREA_CODE;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME_ERROR;

/**
 * Created by tangjie on 2017/11/9.
 */

public class ClassifyActivity extends BaseActivity {

    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.classify_content)
    LinearLayout classifyContent;
    @BindView(R.id.ll_choice_address)
    LinearLayout llChoiceAddress;
    @BindView(R.id.topbar_title)
    TextView topbarTitle;
    @BindView(R.id.topbar_right)
    TextView topbarRight;
    @BindView(R.id.tv_address)
    TextView tvAddress;


    private List<ClassifyTabView> mTabViewList;

    private List<Classify.CategoriesBean> categoriesBeans;
    private ClassifyTabFragment classifyTabFragment;
    private OpenAreas.AreasBean areasBean;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object resp) {/* Do something */
        if (resp instanceof OpenAreas.AreasBean) {
            areasBean = (OpenAreas.AreasBean) resp;
            tvAddress.setText(areasBean.getName());
            AREA_CODE = areasBean.getId();
            UserInfoUtil.AREA_CODE_NAME = areasBean.getName();
        }

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        tvAddress.setText(UserInfoUtil.AREA_CODE_NAME);

        topbarTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String parms = "search?" + "&area_id=" + UserInfoUtil.AREA_CODE + "&latitude=" + UserInfoUtil.mLatitude
                        + "&longitude=" + UserInfoUtil.mLongitude;
                toWebView(parms);
            }
        });

        mTabViewList = new ArrayList<>();
        classifyTabFragment = new ClassifyTabFragment();
        //  switchFragment(1);
        queryData();
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setChecked(v.getId());
        }
    };

    private void setChecked(int index) {
        switchFragment(index);
        for (int i = 0; i < mTabViewList.size(); i++) {
            mTabViewList.get(i).setChecked(index == i);
        }
    }

    private void switchFragment(int index) {
        ClassifyTabView classifyTabView = mTabViewList.get(index);
        if (classifyTabFragment.isAdded()) {
            classifyTabFragment.update(classifyTabView.getCategoriesBean());
        } else {
            Bundle bundle = new Bundle();
            bundle.putSerializable("been", classifyTabView.getCategoriesBean());
            classifyTabFragment.setArguments(bundle);
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.fl_classify_right_container,
                    classifyTabFragment);
            ft.commit();
        }

    }

    private void queryData() {
        String url = API.GOODS_CATEGORY;
        progress.setVisibility(View.VISIBLE);

        HashMap<String, String> headers = new HashMap<>();
        headers.put("Accept", "*/*");

        TypeToken<Classify> typeToken = new TypeToken<Classify>() {
        };

        OkHttpUtils.get().url(url).headers(headers).build().execute(new ObjectCallBack<Classify>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != progress) {
                    progress.setVisibility(View.GONE);
                }
            }

            @Override
            public void onResponse(Classify response, int id) {
                classifyContent.removeAllViews();
                mTabViewList.clear();
                if (null != response) {
                    if (response.getErr_code() == 0) {
                        categoriesBeans = response.getCategories();
                        if (null != categoriesBeans && !categoriesBeans.isEmpty()) {
                            int size = categoriesBeans.size();
                            for (int i = 0; i < size; i++) {
                                Classify.CategoriesBean bean = categoriesBeans.get(i);
                                ClassifyTabView tabView = new ClassifyTabView(getApplicationContext());
                                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.dimen_60));
                                tabView.setLayoutParams(layoutParams);
                                tabView.setId(i);
                                tabView.setCategoriesBean(bean);
                                String name = bean.getName();
                                if (TextUtils.isEmpty(name)) {
                                    tabView.setText("无名氏");
                                } else {
                                    tabView.setText(bean.getName());
                                }
//                                Log.e("1234","size "+ i +"  is "+bean.getName());

                                classifyContent.addView(tabView);
                                mTabViewList.add(tabView);
                            }

                            for (ClassifyTabView tabView : mTabViewList) {
                                tabView.setOnClickListener(mOnClickListener);
                            }

                            setChecked(0);
                        }
                    }

                    else if(response.getErr_code() == TOKEN_OUT_TIME ||response.getErr_code() == TOKEN_OUT_TIME_ERROR){
                        UserInfoUtil.intoLogin(ClassifyActivity.this);
                    }

                    else {
                        showToast(response.getErr_msg());
                    }
                }

                if (null != progress) {
                    progress.setVisibility(View.GONE);
                }
            }
        });
    }


    @OnClick({R.id.ll_choice_address, R.id.topbar_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_choice_address:
                break;
            case R.id.topbar_right:
                Intent intent = new Intent(getBaseContext(), CheckActivity.class);
                startActivity(intent);
                break;
        }
    }

    @OnClick(R.id.ll_choice_address)
    public void onClick() {
        Intent intent = new Intent(getBaseContext(), CityListActivity.class).putExtra("type",1);
        startActivity(intent);
    }

    private void toWebView(String param) {
        Intent intent = new Intent(getBaseContext(), WebActivity.class);
        intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, param);
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
